# -*- coding: utf-8 -*-
import os
import sys
import configparser


class IniParser(object):
    def __init__(self):
        self.config_file = os.path.join(os.path.dirname(__file__), 'config.ini')
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file)

    def get(self, section, key, raw=False):
        """
        读取ini配置文件，作为字符串返回
        :param section: 区块
        :param key: 键名
        :param raw: 值中含有特殊字符，如%时，raw设置为True
        :return:
        """
        try:
            value = self.config.get(section, key, raw=raw)
            return value
        except Exception as e:
            raise e

    def getint(self, section, key):
        """
        读取ini配置文件，作为int类型返回
        :param section:
        :param key:
        :return:
        """
        try:
            value = self.config.getint(section, key)
            return value
        except Exception as e:
            raise e

    def getbool(self, section, key):
        """
        读取ini配置文件，作为bool类型返回
        :param section:
        :param key:
        :return:
        """
        try:
            value = self.config.getboolean(section, key)
            return value
        except Exception as e:
            raise e

    def getfloat(self, section, key):
        """
        读取ini配置文件，作为float类型返回
        :param section:
        :param key:
        :return:
        """
        try:
            value = self.config.getboolean(section, key)
            return value
        except Exception as e:
            raise e

    def write(self, section, key, value):
        """
        写入ini配置文件，原配置文件中的注释部分会丢失
        :param section: 区块
        :param key: 键名
        :param value: 值
        :return:
        """
        try:
            self.config.set(section, key, value)
            with open(self.config_file, 'w') as file:
                self.config.write(file)
        except Exception as e:
            raise e


ini_parse = IniParser()

if __name__ == '__main__':
    print(ini_parse.get('common', 'MongoHost'))
    ini_parse.write('common', 'MongoHost', '127.0.0.1')
    ini_parse.write('common', 'MongoPort', '12345')
